import jsapi from '@/utils/arcgis/jsapi';
import { IToken } from '../../../types/portal';

interface IEnterpriseAuth {
  portalUrl: string;
  signIn: (username: string, password: string) => Promise<IToken>;
}

export default class EnterpriseAuth implements IEnterpriseAuth {
  portalUrl: string;

  constructor({ portal }) {
    this.portalUrl = portal;
  }

  signIn(username, password) {
    const that = this;

    return new Promise<IToken>((resolve, reject) => {
      jsapi
        .load(['esri/identity/IdentityManager', 'esri/identity/ServerInfo'])
        .then(([esriId, ServerInfo]) => {
          const info = new ServerInfo({
            server: that.portalUrl,
            tokenServiceUrl: that.portalUrl + 'sharing/rest/generateToken',
          });

          esriId.registerServers([info]);
          esriId
            .generateToken(info, {
              username,
              password,
            })
            .then(tokenResp => {
              if (tokenResp) {
                esriId.registerToken({
                  server: that.portalUrl,
                  ssl: true,
                  token: tokenResp.token,
                  userId: username,
                  expires: tokenResp.expires,
                });

                resolve({
                  token: tokenResp.token,
                  expires: tokenResp.expires,
                  path: '/',
                  domain: that.portalUrl,
                });
              } else {
                reject(null);
              }
            })
            .catch(() => reject(null));
        });
    });
  }
}
